package com.wanxi.chat.messagehandler.auth;

import com.alibaba.fastjson.JSONObject;
import com.wanxi.chat.codec.Invocation;
import com.wanxi.chat.dispatcher.MessageHandler;
import com.wanxi.chat.message.auth.AuthRequest;
import com.wanxi.chat.message.auth.AuthResponse;
import com.wanxi.chat.model.ChatEntity;
import com.wanxi.chat.offline.api.OfflineFeignClient;
import com.wanxi.chat.result.CommonResult;
import com.wanxi.chat.server.NettyChannelManager;
import io.netty.channel.Channel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Map;

@Component
public class AuthRequestHandler implements MessageHandler<AuthRequest> {

    @Autowired
    private NettyChannelManager nettyChannelManager;

    @Autowired
  private   OfflineFeignClient offlineFeignClient;
    @Override
    public void execute(Channel channel, AuthRequest authRequest) {
        // 如果未传递 accessToken
        if (StringUtils.isEmpty(authRequest.getUserId())) {
            AuthResponse authResponse = new AuthResponse().setCode(1).setMessage("用户id信息 未传入");
            channel.writeAndFlush(new Invocation(AuthResponse.TYPE, authResponse));
            return;
        }

        // 将用户和 Channel 绑定
        nettyChannelManager.addUser(channel, authRequest.getUserId());
        ChatEntity chatEntity=new ChatEntity();
        chatEntity.setId(authRequest.getUserId());
        CommonResult pull = offlineFeignClient.redisPullFeign(chatEntity);
        Object data = pull.getData();
       Map map= (Map) data;
        String content = (String) map.get("content");
        JSONObject resultStr = (JSONObject) JSONObject.parse(content);
        String string = resultStr.getString("content");
        // 响应认证成功
        AuthResponse authResponse = new AuthResponse();
        authResponse.setCode(0);
      authResponse.setMessage(string);
        channel.writeAndFlush(new Invocation(AuthResponse.TYPE, authResponse));
    }

    @Override
    public String getType() {
        return AuthRequest.TYPE;
    }

}
